<template>
    <div id="container">
        <my-header></my-header>
        <el-main id="main">
            <!-- 标题 -->
            <div id="title">
                <div id="title-text">
                    <span id="type">[{{basic.type}}]</span> {{basic.title}}
                    <span id="recommend-tag" v-if="basic.recommend_tag == 1"></span>
                </div>
            </div>
            <div id="title-button">
                <el-button type="primary" icon="el-icon-download" round id="download_button" @click="download">下载</el-button>
                <el-button type="success" icon="el-icon-share" round id="download_button" @click="setRecommend" v-if="this.$store.state.login.role == 1">推荐给其他人</el-button>
            </div>
            <!-- 分割线 -->
            <el-divider></el-divider>
            <!-- 基本信息 -->
            <div id="basic-info">
                <i class="el-icon-user"></i> {{basic.uploader}}&nbsp;&nbsp;&nbsp;
                <i class="el-icon-time"></i> {{basic.time}}&nbsp;&nbsp;&nbsp;
                <i class="el-icon-location-information"></i> {{current_location}}&nbsp;&nbsp;&nbsp;
                <i class="el-icon-notebook-1"></i> {{basic.course}}
            </div>
            <!-- 版本和下载次数 -->
            <div id="version">
                <el-button type="primary" icon="el-icon-files" round size="mini">版本：V{{basic.version}}</el-button>
                <el-button type="success" icon="el-icon-download" round size="mini">下载次数：{{basic.download_count}}次</el-button>
            </div>
            <!-- 标签 -->
            <div>
                <el-tag v-for="(item,index) in basic.tags" v-bind:key="index" id="tag">{{item}}</el-tag>
                <el-rate
                    id="rate"
                    v-model="basic.score"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}">
                </el-rate>
            </div>
            <!-- 资源描述 -->
            <div id="desc">
                <span id="item-title">资源描述</span>
                <div id="desc-box">
                    {{basic.desc}}
                </div>
            </div>
            <!-- 教师推荐 -->
            <div id="recommend" v-if="basic.recommend_tag === 1">
                <span id="item-title">教师推荐</span>
                <div id="recommend-box" v-for="(item,index) in recommend" :key="index">
                    <span id="recommend-banner"></span>
                    {{item.reason}}
                    <p>{{item.teacher}} 推荐于 {{item.time}}</p>
                    <el-divider></el-divider>
                    <div id="like">
                        <span class="like-icon" :class="item.likeStatus" @click="handleLikeClick(item)"></span>&nbsp;{{item.like}} &nbsp;&nbsp;&nbsp;&nbsp;
                        <span class="like-icon dislike-icon" :class="item.dislikeStatus" @click="handleDisLikeClick(item)"></span>&nbsp;{{item.dislike}}
                    </div>
                </div>
            </div>
            <!-- 预览 -->
            <!-- <div id="preview">
                <span id="item-title">资源预览</span>
                <el-link type="success" v-if="preview">本资源支持在线预览，请点此预览</el-link>
                <el-link type="danger" v-else>本资源不支持在线预览，请下载后查看</el-link>
            </div> -->
            <!-- 版本历史 -->
            <div id="history">
                <span id="item-title">历史版本</span>
                <el-timeline id="timeline">
                    <el-timeline-item v-for="(item, index) in history_version"
                        :key="index" :timestamp="item.time" placement="top">
                        <el-card>
                            <h4>更新 {{item.version_id}} 版本</h4>
                            <span>更新内容：{{item.update_reason}}</span>
                            <p>{{item.uploader}} 提交于 {{item.time}}</p>
                        </el-card>
                    </el-timeline-item>
                </el-timeline>
            </div>
            <!-- 我的评价 -->
            <div class="my-commit">
                <span id="item-title">我要评价</span>
                <el-card id="commit-box">
                    <div id="item-title">我对该资源的评分是：</div>
                    <el-rate
                        v-model="rateValue"
                        :colors="colors"
                        id="rate">
                    </el-rate>
                    <div class="clear"></div>
                    <div id="item-title">发表评论：</div>
                    <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入评论内容"
                        v-model="commentContent">
                    </el-input>
                    <el-button type="primary" @click="handleCommentClick" id="commit-button" size="small">提交评论</el-button>
                </el-card>
            </div>
            <!-- 评论 -->
            <div id="commit">
                <span id="item-title">评论</span>
                <el-timeline id="timeline">
                    <el-timeline-item v-for="(item, index) in comments"
                        :key="index" :timestamp="item.time" placement="top"
                        color="#0bbd87"
                        size= 'large'
                        icon='el-icon-chat-line-round'>
                        <el-card>
                            <h4>{{item.content}} </h4>
                            <p>{{item.username}} 评论于 {{item.time}}</p>
                        </el-card>
                    </el-timeline-item>
                    <div v-if="comments.length == 0 ">暂无评论</div>
                </el-timeline>
            </div>
        </el-main>
        <my-footer></my-footer>
    </div>
</template>

<script>
import MyFooter from '../../components/MyFooter.vue';
import MyHeader from '../../components/MyHeader.vue'
import axios from 'axios';
export default {
    name:'Detail',
    data:function(){
        return{
            basic:{
                
            },
            recommend:{},
            history_version:[],
            comments:[],
            rateValue:0,
            commentContent:"",
            colors:['#99A9BF', '#F7BA2A', '#FF9900'],
            // 关于教师推荐的点赞
            // likeStatus:'like',
            // dislikeStatus:'dislike'
            current_location:[]

        }
    },
    computed:{
        // 将文件类型转换为全大写
        // upper_type:function() {
        //     return this.basic.type.toUpperCase();
        // },
        // // 评分值
        // value:function(){
        //     return this.detail.score;
        // },
        // 判断文件是否可预览
        preview:function(){
            if(this.basic.type === 'WORD' || this.basic.type === 'PPT' || this.basic.type === 'EXCEL' || this.basic.type === 'PDF'){
                return true;
            }else{
                return false;
            }
        }
    },
    mounted:function(){
        this.getBasic();
        this.getVersion();
        this.getComments();
        this.getRecommend();
        this.getFileLocation();
    },
    methods:{
        setRecommend:function(){
            this.$prompt('请输入推荐语', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(async ({ value }) => {
                let post_data = {
                    reason:value,
                    uid:this.$store.state.login.uid,
                    username:this.$store.state.login.username,
                    file_id:this.$route.query.id
                }
                const headerConfig = { headers:
                    { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                };
                try{
                    const res = await axios.post('/api/detail/commit_recommend',post_data,headerConfig);
                    if(res.status!==200) return this.$message.error("提交失败，请检查网络设置！");
                    if(res.data.res.ok === 1){
                        this.$notify({
                            title: '成功',
                            message: res.data.res.msg,
                            type: 'success'
                        });
                        this.$router.go(0);
                    }else{
                        this.$notify({
                            title: '失败',
                            message: res.data.res.msg,
                            type: 'error'
                        });
                    }
                }catch(e){
                    console.log(e);
                    this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });       
            });
        },
        handleCommentClick:async function(){
            if(this.commentContent == ''){
                this.$message.error('评论内容不能为空！');
                return;
            }
            let post_data = {
                'file_id':this.$route.query.id,
                'uid':this.$store.state.login.uid,
                'username':this.$store.state.login.username,
                'rateValue':this.rateValue,
                'commentContent':this.commentContent
            }
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/comment/commit_comment',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    this.$notify({
                        title: '成功',
                        message: res.data.res.msg,
                        type: 'success'
                    });
                    this.$router.go(0);
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        handleLikeClick:async function(item){
            if(item.likeStatus === 'like'){
                item.likeStatus = 'liked';
                item.like++;
            }else{
                item.likeStatus = 'like';
                item.like--;
            }
            // 发起请求
            let post_data = {
                file_id:this.$route.query.id,
                uid:item.uid,
                like:item.like,
                dislike:item.dislike
            }
            console.log(post_data);
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/detail/commit_like',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        handleDisLikeClick:async function(item){
            if(item.dislikeStatus === 'dislike'){
                item.dislikeStatus = 'disliked';
                item.dislike++;
            }else{
                item.dislikeStatus = 'dislike';
                item.dislike--;
            }
            // 发起请求
            let post_data = {
                file_id:this.$route.query.id,
                uid:item.uid,
                like:item.like,
                dislike:item.dislike
            }
            console.log(post_data);
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/detail/commit_like',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 获取资源基本信息
        getBasic:async function(){
            let post_data = {
                file_id:this.$route.query.id
            }
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/detail/basic',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    // console.log(res);
                    this.basic = res.data.res.data;
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 获取资源位置信息
        async getFileLocation(){
            console.log("get file loaction working...");
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            let post_data = {
                file_id:this.$route.query.id
            }
            try{
                const res = await axios.post('/api/common/get_location',post_data,headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.current_location = res.data.res.data.join(' → ');
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 获取资源版本信息
        getVersion:async function(){
            let post_data = {
                file_id:this.$route.query.id
            }
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/detail/version',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    // console.log(res);
                    this.history_version = res.data.res.data;
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 获取评论信息
        getComments:async function(){
            let post_data = {
                file_id:this.$route.query.id
            }
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/detail/comments',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    this.comments = res.data.res.data;
                }else{
                    console.log("暂无评论");
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 获取教师推荐信息
        getRecommend:async function(){
            let post_data = {
                file_id:this.$route.query.id
            }
            const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
              const res = await axios.post('/api/detail/get_recommend',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                    // console.log(res);
                    this.recommend = res.data.res.data;
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 下载
        download:async function(){
            let filename = this.basic.download_url.split('\\');
            filename = filename[1];
            
            let post_data = {
                file_id:this.$route.query.id,
                path:this.basic.download_url,
                filename:filename,
                originalname:this.basic.originalname
            }
            console.log(post_data);
            try{
                const res = await axios.post('/api/file_download/download_single',post_data,{responseType: 'blob'});
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                console.log(res);
                const { data, headers } = res
                const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
                // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
                //const blob = new Blob([JSON.stringify(data)], ...)
                const blob = new Blob([data],{type: headers['content-type']})
                let dom = document.createElement('a')
                let url = window.URL.createObjectURL(blob)
                dom.href = url
                dom.download = decodeURI(fileName)
                dom.style.display = 'none'
                document.body.appendChild(dom)
                dom.click()
                dom.parentNode.removeChild(dom)
                window.URL.revokeObjectURL(url)
            }catch(e){
                console.log(e);
                // this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        }
    },
    components:{
        MyHeader,
        MyFooter
    }
}
</script>

<style lang="scss" scoped>
#container{
    width: 100%;
    background-color: #eee;
    min-width: 950px;
    #main{
        width:70%;
        margin-left: 15%;
        margin-right: 15%;
        margin-top:30px;
        margin-bottom:30px;
        background-color: #fff;
        box-sizing: border-box;
        padding:50px;
        #title{
            width: 100%;
            font-size: 28px;
            font-weight: bold;
            position: relative;
            #title-text{
                width:72%;
                display: block;
                float: left;
                #type{
                    color: #409EFF;
                }
            }
            #title-button{
                width:28%;
                display: block;
                float: right;
                #download_button{
                    float:right;
                    display: block;
                    margin-top: -10px;
                    margin-left:10px;
                }
            }
        }
        /deep/ .el-divider{
            margin: 20px;
            margin-left: 0;
            margin-right: 0;
        }
        #basic-info{
            margin-bottom: 15px;
        }
        #version{
            margin-bottom: 10px;
        }
        #tag{
            margin-right: 20px;
        }
        #rate{
            display: block;
            float:right;
        }
        #desc,#recommend{
            margin-top:15px;
            #desc-box,#recommend-box{
                margin-top:10px;
                background-color: #eee;
                padding: 40px;
                border-radius: 6px;
                position: relative;
                line-height: 30px;
                p{
                    font-size: 12px;
                    color:grey;
                    line-height: 20px;
                }
                /deep/ .el-divider{
                    margin: 10px;
                    margin-left: 0;
                    margin-right: 0;
                }
                #like{
                    .like-icon{
                        width: 15px;
                        height: 15px;
                        display: inline-block;
                        background-size:15px 15px;
                        background-repeat:no-repeat;
                        background-position:top center;
                        background-color: transparent;
                        background-image: url("~@/assets/icons/like.png");
                    }
                    .dislike-icon{
                        background-image: url("~@/assets/icons/dislike.png");
                    }
                    .liked{
                        background-image: url("~@/assets/icons/liked.png");
                    }
                    .disliked{
                        background-image: url("~@/assets/icons/disliked.png");
                    }
                    .like-icon:hover{
                        cursor: pointer;
                    }
                }
            }
            #recommend-box{
                padding-bottom: 10px;
            }
        }
        #preview{
            margin-top:15px;
        }
        #history,#commit{
            margin-top:15px;
            #timeline{
                margin-top:15px;
                line-height: 30px;
            }
        }
        .clear{
            clear:both;
        }
        #commit-box{
            margin-top:15px;
            padding: 20px;
            #item-title{
                float: left;
                font-size: 16px;
                font-weight: normal;
                margin-bottom:10px;
            }
            #rate{
                display: block;
                float: left;
            }
            #commit-button{
                margin-top: 20px;
            }
        }
    }
}
#item-title{
    font-weight: bold;
    margin-right: 10px;
    font-size: 20px;
}
#recommend-tag{
    width: 50px;
    height: 32px;
    display: inline-block;
    background-size:40px 40px;
    background-repeat:no-repeat;
    background-position:top center;
    background-color: transparent;
    background-image: url("~@/assets/icons/recommend.png");
    position:absolute;
    top:-6px;
}
#recommend-banner{
    width: 50px;
    height: 50px;
    display: inline-block;
    background-size:50px 50px;
    background-repeat:no-repeat;
    background-position:top center;
    background-color: transparent;
    background-image: url("~@/assets/icons/recommend2.png");
    position:absolute;
    top:0px;
    left:0px;
}
</style>